import React, {Component, Fragment} from 'react';
import {Card, Table, Image, message, Input, Button} from 'antd';
import {reqImages, reqDeleteImages} from '../../api/picture';
import {Link} from 'react-router-dom';
import moment from "moment";
import './less/index.less';

const {Search} = Input;

// 图片
export default class Images extends Component {
  pageQuery = {} // 保存页面信息
  state = {
    totalCount: 0,
    list: [],
    loading: false,
    searchLoading: false,
    selectedRowKeys: [], // 选择删除
  }
  initColumns = () => {
    this.columns = [
      {
        title: '标题',
        dataIndex: 'title',
        align: 'center',
        render: (text, record) => <Link to={'/admin/pictures/' + record._id}>{record.title}</Link>
      },
      {
        title: '地区',
        dataIndex: 'area',
        align: 'center',
        render: (text) => text === '' ? '-' : text,
      },
      {
        title: '图片',
        dataIndex: 'image',
        align: 'center',
        render: (image) => <Image src={image} width={88}/>
      },
      {
        title: '发布时间',
        dataIndex: 'add_time',
        align: 'center',
        render: (add_time) => moment(add_time).format('YYYY-MM-DD')
      }
    ]
  }

  UNSAFE_componentWillMount() {
    this.initColumns();
  }
  // 获取图片
  getImages = async (data = {}) => {
    try {
      this.setState({loading: true});
      const {data: result} = await reqImages(data);
      this.setState({
        list: result.items,
        totalCount: result.total_count,
        loading: false,
        searchLoading: false,
      })
    } catch (e) {
      this.setState({loading: false});
      message.error(e.data.name || e.data.message)
    }
  }
  // 改变分页设置
  onChange = (pagination, filters, sorter, extra) => {
    const {current, pageSize} = pagination;
    let data = {page: current, page_size: pageSize}
    if (this.search) {
      data = Object.assign(data, {q: this.search});
    }
    this.getImages(data);
    this.pageQuery = data;
  }
  // 搜索
  onSearch = (value, event) => {
    if (value !== '') {
      this.setState({searchLoading: true});
      this.search = value;
      this.getImages({q: value});
      this.pageQuery = {q: value};
    } else if (value === '' && this.search !== '') {
      this.search = '';
      this.getImages();
      this.pageQuery = {};
    }
  }
  // 选择
  onSelectChange = selectedRowKeys => {
    this.setState({ selectedRowKeys });
  };

  // 删除图片
  deleteImages = async (data) => {
    try {
      await reqDeleteImages(data);
      message.success('删除成功');
      this.getImages(this.pageQuery);
    } catch (e) {
      message.error(e.data.message);
    }
  }

  // 删除
  onDeleteClick = () => {
    const { selectedRowKeys } = this.state;
    if (selectedRowKeys.length > 0) {
      this.deleteImages({items: selectedRowKeys});
    } else {
      message.warning('至少选择一项');
    }
  }

  // 发起请求
  componentDidMount() {
    this.getImages();
  }


  render() {
    const {totalCount, list, loading, searchLoading, selectedRowKeys} = this.state;
    const pagination = {
      defaultPageSize: 10,
      position: ['bottomCenter'],
      showQuickJumper: true,
      total: totalCount,
    };
    // 启用带选择的框
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };

    // 卡片右侧自定义
    const extra = (
      <Fragment>
        <Button type="primary" danger onClick={this.onDeleteClick}>删除</Button>
      </Fragment>
    )

    return (
      <Card title='图片' extra={extra}>
        <div className='search-box'>
          <Search placeholder="搜索标题，地区"
                  onSearch={this.onSearch}
                  style={{width: 200}}
                  loading={searchLoading}/>
        </div>
        <Table
          onChange={this.onChange}
          pagination={pagination}
          scroll={{x: 800}}
          loading={loading}
          rowSelection={rowSelection}
          columns={this.columns}
          dataSource={list}
          rowKey='_id'
        />
      </Card>
    )
  }
}
